package com.tanhua.commons.baidu.utils;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.tanhua.commons.baidu.config.AipConfig;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.util.HashMap;

@Component
public class AipUtils {

    @Autowired
    private AipConfig aipConfig;

    public boolean detect(byte[] bytes) {

        String image = Base64Util.encode(bytes);

        AipFace client = new AipFace(aipConfig.getAppId(), aipConfig.getApiKey(), aipConfig.getSecretKey());
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("liveness_control", "LOW");

        // 人脸检测
        JSONObject res = client.detect(image, "BASE64", options);
        System.out.println(res.toString(2));
        int errorCode = res.getInt("error_code");
        if(errorCode == 0) {
            int faceNum =  res.getJSONObject("result").getInt("face_num");
            return faceNum==1;
        }else{
            return false;
        }
    }
}
